/**
 * MetadataSearchPage
 * 元数据搜索页面
 * Features: 关键字搜索、数据源筛选、表类型筛选、搜索结果展示
 */

import React, { useState } from 'react'
import { Card, Input, Select, Table, Tag, Space, Button } from 'antd'
import { SearchOutlined, DatabaseOutlined, TableOutlined } from '@ant-design/icons'
import { useNavigate } from 'react-router-dom'
import type { ColumnsType } from 'antd/es/table'
import { useSearchTables, usePrefetchTableDetail } from '@/hooks/useMetadata'
import { useDataSourceList } from '@/hooks/useDataSource'
import type { MetadataTable } from '@/services/models/types'
import { TableType } from '@/services/models/types'

const { Search } = Input

// 表类型标签配置
const TABLE_TYPE_CONFIG: Record<TableType, { color: string; text: string }> = {
  [TableType.TABLE]: { color: 'blue', text: '表' },
  [TableType.VIEW]: { color: 'cyan', text: '视图' },
  [TableType.MATERIALIZED_VIEW]: { color: 'purple', text: '物化视图' },
}

export const MetadataSearchPage: React.FC = () => {
  const navigate = useNavigate()
  const prefetchTableDetail = usePrefetchTableDetail()

  const [searchParams, setSearchParams] = useState({
    keyword: '',
    datasourceId: undefined as number | undefined,
    tableType: undefined as TableType | undefined,
    page: 0,
    size: 10,
  })

  // 查询元数据表
  const { data: tableData, isLoading } = useSearchTables(searchParams)

  // 查询数据源列表(用于筛选)
  const { data: datasourceData } = useDataSourceList({ page: 0, size: 100 })

  // 表格列定义
  const columns: ColumnsType<MetadataTable> = [
    {
      title: '表名',
      dataIndex: 'tableName',
      width: 200,
      render: (tableName, record) => (
        <Button
          type="link"
          icon={<TableOutlined />}
          onClick={() => navigate(`/metadata/${record.id}`)}
          onMouseEnter={() => prefetchTableDetail(record.id)}
        >
          {record.schemaName ? `${record.schemaName}.${tableName}` : tableName}
        </Button>
      ),
    },
    {
      title: '类型',
      dataIndex: 'tableType',
      width: 100,
      render: (tableType: TableType) => {
        const config = TABLE_TYPE_CONFIG[tableType]
        return <Tag color={config.color}>{config.text}</Tag>
      },
    },
    {
      title: '数据源',
      dataIndex: 'datasourceName',
      width: 150,
      render: (datasourceName, record) => (
        <Space>
          <DatabaseOutlined />
          <span>{datasourceName}</span>
          <Tag>{record.datasourceStatus}</Tag>
        </Space>
      ),
    },
    {
      title: '注释',
      dataIndex: 'tableComment',
      ellipsis: true,
      render: (comment) => comment || '-',
    },
    {
      title: '行数',
      dataIndex: 'rowCount',
      width: 120,
      align: 'right',
      render: (rowCount) => (rowCount ? rowCount.toLocaleString() : '-'),
    },
    {
      title: '大小',
      dataIndex: 'sizeInBytes',
      width: 120,
      align: 'right',
      render: (sizeInBytes) => {
        if (!sizeInBytes) return '-'
        if (sizeInBytes < 1024) return `${sizeInBytes} B`
        if (sizeInBytes < 1024 * 1024) return `${(sizeInBytes / 1024).toFixed(2)} KB`
        if (sizeInBytes < 1024 * 1024 * 1024) return `${(sizeInBytes / (1024 * 1024)).toFixed(2)} MB`
        return `${(sizeInBytes / (1024 * 1024 * 1024)).toFixed(2)} GB`
      },
    },
    {
      title: '更新时间',
      dataIndex: 'updatedAt',
      width: 180,
    },
  ]

  // 处理搜索
  const handleSearch = (keyword: string) => {
    setSearchParams((prev) => ({ ...prev, keyword, page: 0 }))
  }

  // 处理数据源筛选
  const handleDatasourceChange = (datasourceId: number | undefined) => {
    setSearchParams((prev) => ({ ...prev, datasourceId, page: 0 }))
  }

  // 处理表类型筛选
  const handleTableTypeChange = (tableType: TableType | undefined) => {
    setSearchParams((prev) => ({ ...prev, tableType, page: 0 }))
  }

  // 清空筛选
  const handleClearFilters = () => {
    setSearchParams({
      keyword: '',
      datasourceId: undefined,
      tableType: undefined,
      page: 0,
      size: 10,
    })
  }

  return (
    <div className="p-6">
      <Card title="元数据搜索">
        {/* 搜索和筛选栏 */}
        <Space direction="vertical" size="middle" className="w-full">
          <Space size="middle" className="w-full">
            <Search
              placeholder="搜索表名或注释"
              allowClear
              enterButton={<SearchOutlined />}
              size="large"
              value={searchParams.keyword}
              onChange={(e) => setSearchParams((prev) => ({ ...prev, keyword: e.target.value }))}
              onSearch={handleSearch}
              style={{ width: 400 }}
            />

            <Select
              placeholder="选择数据源"
              allowClear
              style={{ width: 200 }}
              value={searchParams.datasourceId}
              onChange={handleDatasourceChange}
            >
              {datasourceData?.content?.map((ds) => (
                <Select.Option key={ds.id} value={ds.id}>
                  {ds.name}
                </Select.Option>
              ))}
            </Select>

            <Select
              placeholder="选择表类型"
              allowClear
              style={{ width: 150 }}
              value={searchParams.tableType}
              onChange={handleTableTypeChange}
            >
              <Select.Option value={TableType.TABLE}>
                <Tag color={TABLE_TYPE_CONFIG[TableType.TABLE].color}>
                  {TABLE_TYPE_CONFIG[TableType.TABLE].text}
                </Tag>
              </Select.Option>
              <Select.Option value={TableType.VIEW}>
                <Tag color={TABLE_TYPE_CONFIG[TableType.VIEW].color}>
                  {TABLE_TYPE_CONFIG[TableType.VIEW].text}
                </Tag>
              </Select.Option>
              <Select.Option value={TableType.MATERIALIZED_VIEW}>
                <Tag color={TABLE_TYPE_CONFIG[TableType.MATERIALIZED_VIEW].color}>
                  {TABLE_TYPE_CONFIG[TableType.MATERIALIZED_VIEW].text}
                </Tag>
              </Select.Option>
            </Select>

            {(searchParams.keyword || searchParams.datasourceId || searchParams.tableType) && (
              <Button onClick={handleClearFilters}>清空筛选</Button>
            )}
          </Space>

          {/* 搜索结果统计 */}
          {tableData && (
            <div className="text-gray-500">
              找到 <span className="font-semibold text-blue-600">{tableData.totalElements}</span> 张表
            </div>
          )}

          {/* 搜索结果表格 */}
          <Table
            columns={columns}
            dataSource={tableData?.content || []}
            rowKey="id"
            loading={isLoading}
            pagination={{
              current: searchParams.page + 1,
              pageSize: searchParams.size,
              total: tableData?.totalElements || 0,
              showSizeChanger: true,
              showTotal: (total) => `共 ${total} 条记录`,
              onChange: (page, size) => setSearchParams((prev) => ({ ...prev, page: page - 1, size })),
            }}
            scroll={{ x: 1200 }}
          />
        </Space>
      </Card>
    </div>
  )
}

export default MetadataSearchPage
